package com.chalk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.chalk.common.constant.TypeConstants;
import com.chalk.common.exception.ServiceException;
import com.chalk.config.security.SecurityPasswordUtil;
import com.chalk.dao.SysUserDao;

import com.chalk.model.Seller;
import com.chalk.model.SysRole;
import com.chalk.model.SysUser;
import com.chalk.model.SysUserRoleRelated;
import com.chalk.service.SellerService;
import com.chalk.service.SysRoleService;
import com.chalk.service.SysUserRoleRelatedService;
import com.chalk.service.SysUserService;
import com.chalk.vo.SysUserVo;
import com.chalk.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 系统用户表(SysUser)表服务实现类
 *
 * @author maxiaoqiang
 * @since 2019-03-22 17:38:25
 */
@Service
@Transactional(rollbackFor = ServiceException.class)
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleRelatedService relatedService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SellerService sellerService;


    /*自定义接口*/

    @Override
    public List<SysUser> getUserByUserName(String userName) {
        return sysUserDao.getUserByUserName(userName);
    }

    /**
     * 根据主键批量(逻辑)删除
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatchByPrimaryKey(String[] ids) {
        return sysUserDao.deleteBatchByPrimaryKey(ids);
    }



    @Override
    public boolean
    insertAndRole(SysUserVo sysUser) {
        /*md5 加密*/
        sysUser.setPassword(SecurityPasswordUtil.md5Encrypt(sysUser.getPassword()));
        super.insert(sysUser);
        insertRole(sysUser.getRoleIds(), sysUser.getUserId());
        return true;
    }


    @Override
    public boolean updateAndRole(SysUserVo sysUser) {
        SysUser oldUser = super.selectById(sysUser.getUserId());
        if(!sysUser.getPassword().equals(oldUser.getPassword())){
            /*md5 加密*/
            sysUser.setPassword(SecurityPasswordUtil.md5Encrypt(sysUser.getPassword()));
        }
        super.updateById(sysUser);
        SysUser user = super.selectById(sysUser.getUserId());
        // 如果为可用
        Seller seller = sellerService.selectById(user.getSellerId());
        if(null != user.getIsAvailable() && null != seller){
            if(TypeConstants.YesOrNo.YES.getValue().equals(user.getIsAvailable())){
                seller.setRunningStatus(1);
            }else if(TypeConstants.YesOrNo.NO.getValue().equals(user.getIsAvailable())){
                seller.setRunningStatus(0);
            }
            // 更新商家状态
            sellerService.updateById(seller);
        }
        /*清除旧的*/
        relatedService.delete(new EntityWrapper<SysUserRoleRelated>().eq("user_id", sysUser.getUserId()));
        /*添加新的*/
        insertRole(sysUser.getRoleIds(), sysUser.getUserId());
        return true;
    }

    /**
     * 插入权限组
     *
     * @param roleIds
     * @param userId
     */
    private void insertRole(String[] roleIds, String userId) {
        SysUserRoleRelated related = null;
        for (String roleId : roleIds) {
            related = new SysUserRoleRelated(roleId, userId);
            relatedService.insert(related);
        }
    }

    @Override
    public SysUser selectOne(Map<String, Object> param) {
        List<SysUser> sysUsers = super.selectByMap(param);
        return sysUsers != null && sysUsers.size() > 0 ? sysUsers.get(0) : null;
    }


    @Override
    public Page<UserVo> getUserByPage(Page<UserVo> page, SysUser sysUser) {
        List<UserVo> userByPage = sysUserDao.getUserByPage(page, sysUser);
        for (UserVo vo : userByPage) {
            String[] roleIds = StringUtils.isEmpty(vo.getRoleIds()) ? null : vo.getRoleIds().split(",");
            if (roleIds != null && roleIds.length > 0) {
                List<SysRole> sysRoles = roleService.selectBatchIds(Arrays.asList(roleIds));
                StringBuilder sb = new StringBuilder();
                sysRoles.forEach(sysRole -> {
                    if (StringUtils.isEmpty(sb.toString())) {
                        sb.append(sysRole.getName());
                    } else {
                        sb.append(",");
                        sb.append(sysRole.getName());
                    }
                });
                vo.setRoleNames(sb.toString());
            }
        }
        return page.setRecords(userByPage);
    }

    @Override
    public List<UserVo> selectListByShopName(Page<UserVo> page, SysUser sysUser) {
        return sysUserDao.selectListByShopName(page,sysUser);
    }
    /**
     * 销售人员查询所属门店
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> searchShopNameByUserId(String userId) {
        return sysUserDao.searchShopNameByUserId(userId);
    }
}